import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  //使用persistedstate插件
  // plugins: [
  //   persistedstate({
  //     storage: window.sessionStorage,
  //     //随便定义一个即可
  //     key: "vuex_store",
  //   }),
  // ],
  state: {
    user: {
      userId: null, //账号id
      nickname: "",
      userRole: null,  // 用户角色(0:管理员,1:客服,3:财务)
      token: "",       // JWT令牌
    },
  },
  getters: {},
  mutations: {
    setUser(state, user) {
      state.user = user;
      // 手动保存到 localStorage
      localStorage.setItem('user', JSON.stringify(user));
    },
    // 从 localStorage 恢复状态
    restoreUser(state) {
      const savedUser = localStorage.getItem('user');
      if (savedUser) {
        state.user = JSON.parse(savedUser);
      }
    }
  },
  actions: {
    // 在应用启动时恢复状态
    async initializeStore({ commit }) {
      commit('restoreUser');
    }
  },
  modules: {},
});
